//用户导入导出等

/**
 * @openapi
 * tags:
 * - name: admin/user
 *   description: 用户数据处理
 */

const router = require("express-promise-router")();

const multer  = require('multer');
const config=require("../../config/config");
const template_file = config.template_file;
const tmp_uploads_dir=config.tmp_uploads_dir; //存放临时上传的文件。导入完成后就可以删除。不做hash处理
const upload = multer({ dest: tmp_uploads_dir });
//console.log('tmp_uploads_dir',tmp_uploads_dir);


const KindService = require("../../services/kind");
const LogService = require("../../services/log");
const UserService=require("../../services/user")
const GoodService=require("../../services/goods");
const EmoocService = require("../../services/emooc");

/**
 * @openapi
 * /teacher/auto_borrow/import/check_file:
 *   post:
 *     tags:
 *     - admin/auto_borrow
 *     summary: 导入用户第一步，检查excel文件
 *     requestBody:
 *       content:
 *         multipart/form-data:
 *           schema:
 *             type: object
 *             properties:
 *               file:
 *                 type: string
 *                 format: binary
 *               nameRowNumber:
 *                 type: number
 *               firstDataRowNumber:
 *                 type: number
 *               fieldsMapping:
 *                 type: object
 *     responses:
 *       200:
 *         description: 返回JSON文件信息
 */
//从excel文件导入用户，可传递标题行与数据开始行，可以传递一个表头映射对象
router.post('/import/check_file', upload.single('file'), async function  (req, res){
    // req.file 是 `users` 文件的信息
    // req.body 将具有文本域数据，如果存在的话
    //req.file.path 是文件路径
    var default_nameRowNumber = 1;
    var default_firstDataRowNumber = 2;
    let {nameRowNumber=default_nameRowNumber,firstDataRowNumber=default_firstDataRowNumber,fieldsMapping}=req.body;
    if(fieldsMapping){
        fieldsMapping=JSON.parse(fieldsMapping);
    }
    //检查Excel文件是否合乎格式
    const result=await KindService.checkExcelFile(req.file.path,nameRowNumber,firstDataRowNumber,fieldsMapping);
    if(result.error){
        return res.status(400).send({"error":result.error});
    }else{
        return res.json(result);
    }
});

/*
{
  "filePath": "C:\\x_项目\\lims_v5\\tmp_uploads\\5ab1bed9b851ff3be2eec9cfc7023b73",
  "nameRowNumber": 6,
  "firstDataRowNumber": 7,
  "fieldsMapping": {"学号":"username"}
}
* */
/**
 * @openapi
 * /teacher/auto_borrow/import/confirm_file:
 *   post:
 *     tags:
 *     - admin/auto_borrow
 *     summary: 导入用户第二步，确认导入excel文件
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               filePath:
 *                 type: string
 *               nameRowNumber:
 *                 type: number
 *               firstDataRowNumber:
 *                 type: number
 *               fieldsMapping:
 *                 type: object
 *       required: true
 *     responses:
 *       200:
 *         description: 返回md5处理的字符串
 */
router.post('/import/confirm_file',  async function  (req, res){
    //从客户端取得要导入的文件路径，由check_file给出
    var default_nameRowNumber = 1;
    var default_firstDataRowNumber = 2;
    let {nameRowNumber=default_nameRowNumber,firstDataRowNumber=default_firstDataRowNumber,filePath,fieldsMapping}=req.body;
    // if(fieldsMapping){
    //     fieldsMapping=JSON.parse(fieldsMapping);
    // }
    //导入到数据库
    const result=await KindService.importExcelFile(filePath,nameRowNumber,firstDataRowNumber,fieldsMapping);
    LogService.addLog(req.session.user,"物料",`导入种类`);
    res.json(result);
});

/**
 * @openapi
 * /teacher/auto_borrow/add:
 *   post:
 *     tags:
 *     - admin/auto_borrow
 *     summary: 创建名单
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               name:
 *                 type: string
 *               usernames:
 *                  type: array
 *                  items:
 *                      type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 返回创建的名单
 */
router.post('/add', async function(req, res) {
    const user=req.session.user;
    let kind=req.body;
    console.log(req.body)
    const result=await KindService.add(kind);
    LogService.addLog(user,"物料",`添加种类${kind.name}`);
    return res.json(result);
});
/**
 * @openapi
 * /teacher/auto_borrow/remove:
 *   post:
 *     tags:
 *     - admin/auto_borrow
 *     summary: 创建名单
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               name:
 *                 type: string
 *               usernames:
 *                  type: array
 *                  items:
 *                      type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 返回创建的名单
 */
router.post('/remove', async function(req, res) {
    const user=req.session.user;
    let kindIds=req.body;
    const result=await KindService.remove(kindIds);
    LogService.addLog(user,"物料",`删除种类${kindIds}`);
    return res.json(result);
});

/**
 * @openapi
 * /teacher/auto_borrow/update:
 *   post:
 *     tags:
 *     - admin/auto_borrow
 *     summary: 更新物料
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               name:
 *                 type: string
 *               usernames:
 *                  type: array
 *                  items:
 *                      type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 返回创建的名单
 */
router.post('/update', async function(req, res) {
    const user=req.session.user;
    let {key,value,id}=req.body;
    const result=await KindService.update(key,value,id);
    LogService.addLog(user,"物料",`更新${id}`);
    return res.json(result);
});
/**
 * @openapi
 * /teacher/auto_borrow/save_borrow_list:
 *   post:
 *     tags:
 *     - admin/auto_borrow
 *     summary: 保存借用列表
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               user:
 *                 type: string
 *               list:
 *                  type: array
 *                  items:
 *                      type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 返回创建的名单
 */
router.post('/save_borrow_list', async function(req, res) {
    let {list, user,isApply,time,hasUsed,whiteListId}=req.body;
    const result=await KindService.save_borrow_list(list, user,isApply,time,hasUsed,null,whiteListId);
    return res.json(result);
});

/**
 * @openapi
 * /teacher/auto_borrow/change_used_count:
 *   post:
 *     tags:
 *     - admin/auto_borrow
 *     summary: 保存借用列表
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               type:
 *                 type: string
 *               list:
 *                  type: array
 *                  items:
 *                      type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 返回创建的名单
 */
router.post('/change_used_count', async function(req, res) {
    let {list,type}=req.body;
    const result=await KindService.change_used_count(list,type);
    return res.json(result);
});


/**
 * @openapi
 * /teacher/kind/save_list:
 *   post:
 *     tags:
 *     - admin/auto_borrow
 *     summary: 更新流水表
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               name:
 *                 type: string
 *               usernames:
 *                  type: array
 *                  items:
 *                      type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 返回创建的名单
 */
router.post('/save_list', async function(req, res) {
    let {listId, finalList}=req.body;
    const result=await KindService.save_list(listId, finalList);
    return res.json(result);
});
/**
 * @openapi
 * /teacher/kind/change_status:
 *   post:
 *     tags:
 *     - admin/auto_borrow
 *     summary: 更新物料状态
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               name:
 *                 type: string
 *               usernames:
 *                  type: array
 *                  items:
 *                      type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 返回创建的名单
 */
router.post('/change_status', async function(req, res) {
    let {listId, value,key}=req.body;
    const result=await KindService.change_status(listId, value,key);
    return res.json(result);
});

/**
 * @openapi
 * /teacher/kind/add_white_list:
 *   post:
 *     tags:
 *     - admin/auto_borrow
 *     summary: 添加白名单
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               name:
 *                 type: string
 *               usernames:
 *                  type: array
 *                  items:
 *                      type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 返回创建的名单
 */
router.post('/change_status', async function(req, res) {
    let {listId, value,key}=req.body;
    const result=await KindService.change_status(listId, value,key);
    return res.json(result);
});



/**
 * @openapi
 * /teacher/kind/users_borrow_list:
 *   post:
 *     tags:
 *     - admin/auto_borrow
 *     summary: 学生借用情况
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               kindId:
 *                 type: string
 *               usernames:
 *                  type: array
 *                  items:
 *                      type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 返回创建的名单
 */
router.post('/users_borrow_list', async function(req, res) {
    let {usernames,kindId}=req.body;
    const result=await KindService.users_borrow_list(usernames,kindId);
    return res.json(result);
});

/**
 * @openapi
 * /teacher/kind/save_koudai_record:
 *   post:
 *     tags:
 *     - admin/auto_borrow
 *     summary: 保存口袋实验箱借还数据
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               kindId:
 *                 type: string
 *               goodId:
 *                 type: string
 *               username:
 *                 type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 返回创建的名单
 */
router.post('/save_koudai_record', async function(req, res) {
    let {kindId,goodId,username,type}=req.body;
    const result=await KindService.save_koudai_record(kindId,goodId,username,type);
    return res.json(result);
});

/**
 * @openapi
 * /teacher/kind/borrow_info:
 *   post:
 *     tags:
 *     - admin/auto_borrow
 *     summary: 根据条码获取借用信息
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               value:
 *                  type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 返回创建的名单
 */
router.post('/borrow_info', async function(req, res) {
    let {value}=req.body;
    let result=await KindService.getBorrowListById(value);
    const user=await UserService.getUserByUserName(result.user);
    result.user=user
    return res.json(result);
});



/**
 * @openapi
 * /teacher/kind/borrow_good:
 *   post:
 *     tags:
 *     - admin/auto_borrow
 *     summary: 根据条码获取借用信息
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               value:
 *                  type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 返回创建的名单
 */
router.post('/borrow_good', async function(req, res) {
    let {barcode,listId,username}=req.body;
    const good=await GoodService.getGoodByBarcode(barcode);
    if(!good){
        return res.status(401).send("未查询到物品！");
    }
    let list=await KindService.getBorrowListById(listId);
    const kind=list.list[0];
    const kindId=kind.kind.objectId||kind.kind._id;
    if(good.kindId!==kindId){
        return res.status(401).send('该物品不是学生申领的物品！')
    }
    if(kind.status==='used'){
        return res.status(401).send('申领的物品已经领取完！')
    }
    if(kind.status==='returned'){
        return res.status(401).send('申领的物品已经归还！')
    }
    //该条物料条码持有人
    await GoodService.change_owner([good.objectId],username);
    kind.status='used';
    kind.goods=[good];
    kind.goodId=good._id;
    await KindService.change_status(listId,[kind],'list');
    const result=await KindService.change_status(listId,true,'hasUsed')
    // 记流水
    kind.goodId=good._id;
    await GoodService.save_record([kind], username, "lend");
    if(good.deviceId){
        await EmoocService.bindDevice(username,good.deviceId)
    }
    return res.json(result);
});


/**
 * @openapi
 * /teacher/kind/return_info:
 *   post:
 *     tags:
 *     - admin/auto_borrow
 *     summary: 根据条码获取归还物品信息
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               value:
 *                  type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 返回创建的名单
 */
router.post('/return_info', async function(req, res) {
    let {barcode}=req.body;
    const good=await GoodService.getGoodByBarcode(barcode);
    if(!good){
        return res.status(401).send("未查询到物品！");
    }
    const user=await UserService.getUserByUserName(good.user);
    const borrowList=await KindService.getUserBorrowList(good.user);
    return res.json({user,borrowList});
});


/**
 * @openapi
 * /teacher/kind/return_good:
 *   post:
 *     tags:
 *     - admin/auto_borrow
 *     summary: 根据条码获取借用信息
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               value:
 *                  type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 返回创建的名单
 */
router.post('/return_good', async function(req, res) {
    let {listId,keycount,checkedKeys,username}=req.body;
    if(!checkedKeys.length) {
        return res.status(401).send("未选择物品！");
    }
    const currentList = await KindService.getBorrowListById(listId)
    const listData = currentList.list.filter(item => item.status === "used");
    let remainList = []; // 未全部归还剩下的
    const newList = listData.map(item => {
        const key=item.key||1
        if(checkedKeys.includes(key)) {
            item.status = "returned";
            if(keycount[key] && keycount[key] !== item.count) {
                // 改变过数量并且改变后的数量不等于全部的
                const all_count = item.count;
                const return_count = keycount[key];
                const remain_count = all_count - return_count;

                // 改变归还的数量
                item.count = return_count;

                // 复制一份并修改数量、状态
                const remainItem = JSON.parse(JSON.stringify(item));
                remainItem.count = remain_count;
                remainList.push(remainItem);
            }
        }
        return item;
    });

    const finalList = newList.concat(remainList);

    await KindService.save_list(listId, finalList);

    // 状态保存有已经归还的
    await KindService.change_status(listId, true,'hasReturn');

    const isReturnAll = !finalList.find(item => item.status === "used");
    // 归还了所有
    if(isReturnAll) {
        await KindService.change_status(listId, false,'hasUsed');
    }

    // 有条码：变更持有人 + (已使用的库存量-归还数量)
    const hasCodeRows = finalList.filter(item => item.kind.hasCode);
    if(hasCodeRows.length) {
        const goodIds = hasCodeRows.map(item => item.goodId);
        await KindService.change_used_count(hasCodeRows, "sub");
        await GoodService.change_owner(goodIds, 'admin');
        const goods=await GoodService.getGoodsByIds(goodIds);
        const deviceId=goods.filter(g=>g.deviceId);
        await EmoocService.unBindDevices(deviceId)
    }

    // 无条码：已使用的库存量-归还数量
    let noCodeRows = finalList.filter(item => !item.kind.hasCode && item.status === "returned");
    if(noCodeRows.length) {
        await KindService.change_used_count(noCodeRows, "sub");
        await GoodService.change_owner(noCodeRows, username, "sub");
    }

    // 归还记录
    const returnList = finalList.filter(item => item.status === "returned");
    await GoodService.save_record(returnList, username, "return");
    return res.json('归还成功');
});


/**
 * @openapi
 * /teacher/kind/complete_fault:
 *   post:
 *     tags:
 *     - admin/auto_borrow
 *     summary: 完成设备维护
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               id:
 *                 type: string
 *               content:
 *                 type: string
 *               url:
 *                 type: string
 *       required: true
 *     responses:
 *       200:
 *         description: 返回创建的名单
 */
router.post('/complete_fault', async function(req, res) {
    let {id,content,url,listId,username}=req.body;
    const result=await KindService.complete_fault(id,content,url,listId,username);
    return res.json(result);
});
router.get('/download_box_records', async function(req, res) {
    const {begin,end}=req.query;
    const result=await KindService.download_box_records(begin,end);
    res.download(result);
});

router.get('/download_records', async function(req, res) {
    const {begin,end}=req.query;
    const result=await KindService.download_records(begin,end);
    res.download(result);
});

router.get('/download_repair_records', async function(req, res) {
    const {begin,end}=req.query;
    const result=await KindService.download_repair_records(begin,end);
    res.download(result);
});
//添加类目
router.post('/add_category', async function(req, res) {
    let {category}=req.body;
    const result=await KindService.add_category(category);
    return res.json(result);
});
//删除类目
router.post('/remove_category', async function(req, res) {
    let {id}=req.body;
    const result=await KindService.remove_category(id);
    return res.json(result);
});
//更新申领清单状态
router.post('/updateStatus', async function(req, res) {
    let {id,status,remark}=req.body;
    const result=await KindService.updateStatus(id,status,remark);
    return res.json(result);
});

module.exports = router;
